package com.hotel.utils;




public class SimpleIdGenerator {
    // 自定义纪元 (2024-01-01)
    private static final long CUSTOM_EPOCH = 1704067200000L; // 从1970-01-01到2024-01-01的毫秒数

    // 每一部分所占用的位数
    private static final int TIMESTAMP_BITS = 41;
    private static final int MACHINE_ID_BITS = 10;
    private static final int SEQUENCE_BITS = 12;

    // 每一部分的最大值
    private static final long MAX_MACHINE_ID = ~(-1L << MACHINE_ID_BITS);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 每一部分左移的位数
    private static final long MACHINE_ID_SHIFT = SEQUENCE_BITS;
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS;

    // 成员变量
    private final long machineId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     * @param machineId 机器ID，必须介于0和1023之间
     */
    public SimpleIdGenerator(long machineId) {
        if (machineId < 0 || machineId > MAX_MACHINE_ID) {
            throw new IllegalArgumentException("Machine ID must be between 0 and " + MAX_MACHINE_ID);
        }
        this.machineId = machineId;
    }

    /**
     * 生成下一个ID
     * @return 下一个唯一ID
     */
    public synchronized long nextId() {
        long currentTimestamp = timestamp();

        if (currentTimestamp < lastTimestamp) {
            throw new IllegalStateException("Clock moved backwards. Refusing to generate id.");
        }

        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            if (sequence == 0) {
                // 序列号溢出，等待下一毫秒
                currentTimestamp = waitNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        lastTimestamp = currentTimestamp;

        return ((currentTimestamp - CUSTOM_EPOCH) << TIMESTAMP_LEFT_SHIFT)
                | (machineId << MACHINE_ID_SHIFT)
                | sequence;
    }

    /**
     * 获取当前时间戳（毫秒）
     * @return 当前时间戳
     */
    private long timestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 等待直到下一毫秒
     * @param lastTimestamp 上一次的时间戳
     * @return 新的时间戳
     */
    private long waitNextMillis(long lastTimestamp) {
        long timestamp = this.timestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timestamp();
        }
        return timestamp;
    }

}
